package com.itheima.demo.Filter;

import com.itheima.demo.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.http.protocol.HttpProcessor;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")  先注释 不然影响Interceotor 拦截器
public class Dofilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("doFilter:+{}");
        //拿到请求地址
        HttpServletRequest request1=(HttpServletRequest) request;
        HttpServletResponse response1=(HttpServletResponse) response;
        String requestURI = request1.getRequestURI();
        //判断是否登录请求
        if (requestURI.indexOf("/login")>=0){
            //放行
            chain.doFilter(request1,response1);
            return;
        }
        //从请求头中获取token
        String token = request1.getHeader("token");
        if (!StringUtils.hasLength(token)){
            //禁止登录 跳到登录
            response1.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //校验 token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            //token如果合法就放行
            chain.doFilter(request1,response1);

        } catch (Exception e) {
            log.info(e.getMessage(),e);
            //禁止访问 返回登录
            response1.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }


    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("init:+{}");
    }



    @Override
    public void destroy() {
        log.info("destroy:+{}");
    }
}
